package com.tuton.javanet.chapter04;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SocketChannel;

public class BlockEchoClient {

	private SocketChannel socketChannel;
	private final int port = 8000;
	
	public BlockEchoClient() throws IOException{
		socketChannel = SocketChannel.open();
		InetAddress ia = InetAddress.getLocalHost();
		InetSocketAddress isa = new InetSocketAddress(ia,port);
		socketChannel.connect(isa);
		System.out.println("This client was already connected to the server ...");
	}
	
	public static void main(String[] args) throws IOException {
		new BlockEchoClient().talk();
	}


	private void talk() throws IOException {
		try{
			BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
			BufferedReader br = getReader(socketChannel.socket());
			PrintWriter pw = getWriter(socketChannel.socket());
			
			String msg = null;
			while((msg = localReader.readLine())!= null){
				pw.println(msg);
				System.out.println("Client got message from server ...\n" + br.readLine());
				if("bye".equalsIgnoreCase(msg)){
					break;
				}
			}
		} catch(IOException e) {
			e.printStackTrace();
		} finally{
			try{
				if(socketChannel != null) {
					socketChannel.close();
				}
				
			} catch(IOException e) {
				e.printStackTrace();
			}
		}
		
	}

	private PrintWriter getWriter(Socket socket) throws IOException {
		OutputStream socketOut = socket.getOutputStream();
		return new PrintWriter(socketOut,true);
	}

	private BufferedReader getReader(Socket socket) throws IOException {
		InputStream socketIn = socket.getInputStream();
		return new BufferedReader(new InputStreamReader(socketIn));
	}

}
